package ace.cmp.spring.data.jdbc.querydsl.core.util;

import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import org.springframework.util.ObjectUtils;

/**
 * .
 *
 * @author Caspar
 */
public class PredicateBuilder {

  private final List<Predicate> predicates;

  private PredicateBuilder() {
    this.predicates = new ArrayList<>();
  }

  private PredicateBuilder(List<Predicate> predicates) {
    this.predicates = predicates;
  }

  public static PredicateBuilder of() {
    return new PredicateBuilder();
  }

  public static PredicateBuilder of(List<Predicate> predicates) {
    return new PredicateBuilder(predicates);
  }

  /**
   * 添加过滤条件,判断方法{@link org.springframework.util.ObjectUtils}.
   *
   * @param value     值参数
   * @param predicateSupplier 过滤条件
   * @return self
   */
  public PredicateBuilder addNotEmpty(Object value, Supplier<Predicate> predicateSupplier) {
    return this.add(!ObjectUtils.isEmpty(value), predicateSupplier);
  }

  /**
   * 添加过滤条件.
   *
   * @param predicate 过滤条件
   * @return self
   */
  public PredicateBuilder add(Predicate predicate) {
    return this.add(true, () -> predicate);
  }

  /**
   * 添加过滤条件.
   *
   * @param condition 是否添加
   * @param predicateSupplier 过滤条件
   * @return self
   */
  public PredicateBuilder add(boolean condition, Supplier<Predicate> predicateSupplier) {
    if (condition) {
      Predicate predicate = predicateSupplier.get();
      if (Objects.nonNull(predicate)) {
        predicates.add(predicate);
      }
    }
    return this;
  }

  public Predicate all() {
    return ExpressionUtils.allOf(predicates);
  }

  public Predicate any() {
    return ExpressionUtils.anyOf(predicates);
  }

  public List<Predicate> getPredicates() {
    return this.predicates;
  }
}
